package org.sny7.openOfflineList.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.sny7.openOfflineList.bean.Games;
import org.sny7.openOfflineList.bean.Gui;
import org.sny7.openOfflineList.gui.Splash;

public class XMLDataManager {
	
	private static Document document;
	
	private XMLDataManager() {
		
	}
	
	@SuppressWarnings("unchecked")
	public static void loadFile(String fileName) {
		File file = new File(PathGetter.getPath() + fileName);
		InputStream inputStream = null;
		ZipFile zipFile = null;
		try {
			zipFile = new ZipFile(file);
			Enumeration<ZipEntry> zipEntryList = (Enumeration<ZipEntry>) zipFile.entries();
			ZipEntry zipEntry;
			while (zipEntryList.hasMoreElements()) {
				zipEntry = zipEntryList.nextElement();
				if (zipEntry.getName().endsWith(".xml")) {
					inputStream = zipFile.getInputStream(zipEntry);
					break;
				}
			}
			SAXReader saxReader = new SAXReader();
			document = saxReader.read(inputStream);
			load();
		} catch (ZipException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (zipFile != null) {
				try {
					zipFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		Splash.close();
	}
	
	@SuppressWarnings("unchecked")
	private static void load() {
		Games.generate(document.selectNodes("/dat/games/game"));
		Gui.generate(document.selectSingleNode("/dat/gui"));
	}

}
